package com.xxxy.jsq.action.level;

import com.xxxy.jsq.dao.LevelDao;
import com.xxxy.jsq.model.Level;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class addLevelServlet
 */
@WebServlet("/addLevelServlet")
public class addLevelServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public addLevelServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        Level model = new Level();
        LevelDao dao = new LevelDao();

        // 获取页面参数
        String levelName = request.getParameter("pidh");
        String levelFlag = request.getParameter("cflag");
        String levelOrderStr = request.getParameter("level_order");

        // 设置模型属性
        if (levelName != null && !levelName.isEmpty()) {
            model.setLevelName(levelName);
        }
        if (levelFlag != null && !levelFlag.isEmpty()) {
            model.setLevelFlag(levelFlag);
        }
        if (levelOrderStr != null && !levelOrderStr.isEmpty()) {
            try {
                model.setLevelOrder(Integer.parseInt(levelOrderStr));
            } catch (NumberFormatException e) {
                // 处理非法输入
                PrintWriter out = response.getWriter();
                out.print("Err");
                out.flush();
                out.close();
                return;
            }
        }

        // 设置创建时间
        model.setLevelCDate(new Date());

        // 调用 DAO 添加数据
        String result = dao.add(model);

        // 返回结果给前端
        PrintWriter out = response.getWriter();
        out.print(result);
        out.flush();
        out.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
